package com.hongru.cms.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.hongru.aspect.annotation.Log;
import com.hongru.cms.entity.*;
import com.hongru.cms.entity.vo.CmsContentListVo;
import com.hongru.cms.entity.vo.CmsCourseVo;
import com.hongru.cms.entity.vo.CmsQuestionProblemVo;
import com.hongru.cms.entity.vo.CmsQuestionVo;
import com.hongru.constant.DictConstant;
import com.hongru.ebean.EbeanUtil;
import com.hongru.ebean.HongRuPage;
import com.hongru.system.entity.SysCategory;
import com.hongru.ums.entity.UmsLikeRecord;
import com.hongru.ums.entity.UmsMember;
import com.hongru.util.BeanUtil;
import com.hongru.util.StringUtil;
import com.hongru.vo.LoginUser;
import com.hongru.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Copyright (c) 1998-2022 北京新鸿儒世纪网络技术有限公司 All Rights Reserved.
 * @Url https://www.xinhongru.com
 * @ClassName CmsApiController
 * @Author salter <salter@vip.163.com>
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/4/1 9:41
 */

@RestController
@RequestMapping("/cms")
@Slf4j
@Api(tags = "CMS接口汇总")
public class CmsApiController {

    @Value(value = "${jo.domain}")
    private String domain;

    @PostMapping("/queryContentPageList")
    @ApiOperation(value = "内容列表", tags = "内容管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "channelCode", value = "栏目编码", example = "C01"),
            @DynamicParameter(name = "title", value = "标题", example = "首页"),
            @DynamicParameter(name = "categoryCode", value = "分类", example = "F01"),
            @DynamicParameter(name = "lbsId", value = "项目ID", example = "d4f227dbe71446eb95a7f2f2f934566a"),
    }))
    public Result<HongRuPage<CmsContentListVo>> queryContentPageList(@RequestBody JSONObject searchObj) {
        searchObj.put("status", DictConstant.STATUS_1);
        searchObj.put("column", "sortNo,createTime");
        searchObj.put("order", "asc,desc");
        HongRuPage<CmsContentListVo> page = EbeanUtil.pageList(searchObj, CmsContentListVo.class);
        //LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        JSONObject searchObjUser = new JSONObject();
        searchObjUser.put("type", DictConstant.LIKE_TYPE_CMSCONTENT);
        searchObjUser.put("operation", DictConstant.LIKE_OPERATION_COLLECT);
        HongRuPage<UmsLikeRecord> umsLikeRecordHongRuPage = EbeanUtil.pageList(searchObjUser, UmsLikeRecord.class);
        List<UmsLikeRecord> records = umsLikeRecordHongRuPage.getRecords();
        List<SysCategory> list = EbeanUtil.initExpressionList(SysCategory.class).isNotNull("icon").findList();
        Map<String, String> collect = list.stream().collect(Collectors.toMap(SysCategory::getCode, SysCategory::getIcon));

        for (CmsContentListVo cmsContentListVo : page.getRecords()) {
            cmsContentListVo.setIsCollect(records.stream().anyMatch(e -> cmsContentListVo.getId().equals(e.getSourceId())));
            cmsContentListVo.setCategoryIcon(collect.get(cmsContentListVo.getCategoryCode()));
        }
        String title = searchObj.getString("title");
        String channelCode = searchObj.getString("channelCode");
        if (StringUtil.isNotEmpty(title) && "C02".equals(channelCode) && page.getRecords().size() > 0) {
            int count = EbeanUtil.initExpressionList(CmsContentSearchLog.class).eq("title", title).findCount();
            if (count == 0) {
                CmsContentSearchLog cmsContentSearchLog = new CmsContentSearchLog();
                cmsContentSearchLog.setTitle(title);
                cmsContentSearchLog.save();
            }
        }


        return Result.OK(page);
    }

    @GetMapping("/getContent/{id}")
    @ApiOperation(value = "内容详情", tags = "内容管理")
    public Result<CmsContentListVo> queryContentById(@PathVariable String id) {
        CmsContent content = EbeanUtil.initExpressionList(CmsContent.class).idEq(id).findOne();
        content.setPv(content.getPv() + 1);
        content.update();
        String detail = content.getDetailCms().replaceAll("jeecg-orm", domain);
        content.setDetailCms(detail);
        CmsContentListVo contentListVo = BeanUtil.copy(content, CmsContentListVo.class);
        CmsContent topImageContent = EbeanUtil.initExpressionList(CmsContent.class).eq("channelCode", "C015").findOne();
        if(null!=topImageContent){
            contentListVo.setTopImage(topImageContent.getImage());
        }
        return Result.OK(contentListVo);
    }

    @GetMapping("/contentShare/{id}")
    @ApiOperation(value = "内容分享", tags = "内容管理")
    public Result<CmsContent> contentShare(@PathVariable String id) {
        CmsContent content = EbeanUtil.initExpressionList(CmsContent.class).idEq(id).findOne();
        content.setShareNum(content.getShareNum() + 1);
        content.update();
        return Result.OK(content);
    }

    @PostMapping("/queryContentSearchLogPageList")
    @ApiOperation(value = "内容搜索日志列表", tags = "内容管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
    }))
    public Result<HongRuPage<CmsContentSearchLog>> queryContentSearchLogPageList(@RequestBody JSONObject searchObj) {
        return Result.OK(EbeanUtil.pageList(searchObj, CmsContentSearchLog.class));
    }

    @PostMapping("/queryQuestionPageList")
    @ApiOperation(value = "健康问卷列表", tags = "健康问卷管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "questionType", value = "问卷类型(2:中医体质问卷 1:整体医学问卷 )", example = "2"),
    }))
    public Result<HongRuPage<CmsQuestion>> queryQuestionPageList(@RequestBody JSONObject searchObj) {
        searchObj.put("status", DictConstant.STATUS_1);
        searchObj.put("pageSize", 3);
        return Result.OK(EbeanUtil.pageList(searchObj, CmsQuestion.class));
    }

    @PostMapping("/queryQuestionProblemPageList")
    @ApiOperation(value = "健康问卷问题列表", tags = "健康问卷管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "questionId", value = "问卷ID", example = "821953ac14e24c3dbb1a33a955e458bf"),
    }))
    public Result<HongRuPage<CmsQuestionProblemVo>> queryQuestionProblemPageList(@RequestBody JSONObject searchObj) {
        searchObj.put("status", DictConstant.STATUS_1);
        HongRuPage<CmsQuestionProblemVo> cmsQuestionProblemHongRuPage = EbeanUtil.pageList(searchObj, CmsQuestionProblemVo.class);
        List<CmsQuestionProblemVo> oQuestionProblemList = cmsQuestionProblemHongRuPage.getRecords();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<CmsMemberQuestionProblem> questionProblemList = EbeanUtil.initExpressionList(CmsMemberQuestionProblem.class).eq("memberId", loginUser.getId()).eq("questionId", searchObj.getString("questionId")).findList();
        Map<String, String> questionProblemMap = questionProblemList.stream().collect(Collectors.toMap(CmsMemberQuestionProblem::getQuestionProblemId, CmsMemberQuestionProblem::getContent));
        for (CmsQuestionProblemVo questionProblem : oQuestionProblemList) {
            questionProblem.setAnswer(questionProblemMap.get(questionProblem.getId()));
        }
        cmsQuestionProblemHongRuPage.setRecords(oQuestionProblemList);
        return Result.OK(cmsQuestionProblemHongRuPage);
    }


    @ApiOperation(value = "提交问卷", tags = "健康问卷管理")
    @ApiOperationSupport(ignoreParameters = {"cmsMemberQuestionProblem.id"})
    @PostMapping(value = "/addMemberQuestionProblem")
    public Result<CmsMemberQuestionProblem> addMemberQuestionProblem(@RequestBody CmsMemberQuestionProblem cmsMemberQuestionProblem) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        cmsMemberQuestionProblem.setMemberId(loginUser.getId());
        CmsMemberQuestionProblem hasMemberQuestionProblem = EbeanUtil.initExpressionList(CmsMemberQuestionProblem.class).eq("memberId", loginUser.getId()).eq("questionProblemId", cmsMemberQuestionProblem.getQuestionProblemId()).findOne();
        if (null == hasMemberQuestionProblem) {
            cmsMemberQuestionProblem.save();
        } else {
            cmsMemberQuestionProblem.setId(hasMemberQuestionProblem.getId());
            cmsMemberQuestionProblem.update();
        }
        String questionId = cmsMemberQuestionProblem.getQuestionId();
        int submitProblemCount = EbeanUtil.initExpressionList(CmsMemberQuestionProblem.class).eq("memberId", loginUser.getId()).eq("questionId", questionId).findCount();
        int problemCount = EbeanUtil.initExpressionList(CmsQuestionProblem.class).eq("questionId", questionId).eq("status", DictConstant.STATUS_1).findCount();
        if (submitProblemCount == problemCount) {
            UmsMember umsMember = new UmsMember();
            umsMember.setId(loginUser.getId());
            CmsQuestion question = EbeanUtil.initExpressionList(CmsQuestion.class).idEq(cmsMemberQuestionProblem.getQuestionId()).findOne();
            if (DictConstant.QUESTION_TYPE_1.equals(question.getQuestionType())) {
                umsMember.setIsZtyxQuestion(DictConstant.COMPLETION_STATUS_2);
            }
            if (DictConstant.QUESTION_TYPE_2.equals(question.getQuestionType())) {
                umsMember.setIsZytzQuestion(DictConstant.COMPLETION_STATUS_2);
            }
            umsMember.update();
        }
        return Result.OK("提交成功");
    }


}
